/*
 * Copyright 2004-2011 Paolo Conte
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jellylab.ojoverse;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Paolo Conte
 */
public class SQLTemplate {

  HashMap conditions = new HashMap();

  public SQLTemplate() {
    conditions.put("name1", "foo");
    conditions.put("name2", "212");
    conditions.put("comment", "a comment");
  }

  public String parse(String sql) throws IllegalArgumentException {
    Pattern pattern = Pattern.compile("\\{([\\w\\.]+)\\}");
    Matcher matcher = pattern.matcher(sql);

    while (matcher.find()) {
      // System.out.println("Text " + matcher.group() + " found. Start at " + matcher.start() + ", end at " + matcher.end() + ".\n");
      String match = matcher.group(1);
      if (conditions.containsKey(match)) {
        sql = sql.replaceFirst("\\{" + match + "\\}", escape(conditions.get(match).toString()));
      }
    }

    return sql;
  }

  protected String escape(String replacement) {
    return replacement.replace("\\", "\\\\").replace("$", "\\$");
  }

  public static void main(String[] args) {
    SQLTemplate template = new SQLTemplate();
    String sql = "SELECT DISTINCT DATA, COUNT(*) AS ROW_NUM"
            + "FROM TAB1 LEFT JOIN TAB2 ON F1 = F2 "
            + "WHERE NAME1 = {NAME1} AND NAME2 = {NAME2} "
            + "GROUP BY DATA "
            + "--{comment}";
    String parsedSQL = template.parse(sql);
    System.out.println(parsedSQL + "\n");
  }
}
